from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_cors import CORS
from toutiao.settings import config_dict,setup_log



app = Flask(__name__)

# 只需要修改key就可以获取到指定的配置类,一劳永逸
Config = config_dict["dev"]

# 设置日志
setup_log(Config)

# 加载配置类
app.config.from_object(Config)

# 创建SQLAchemy实例
db = SQLAlchemy(app)

#创建Redis实例:默认使用0号库
# redis_store=redis.StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT)

# current_app 方便我们抽取代码,在这里使用app比上面的方便一些
app.redis_store=redis.StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT)

# 设置CORS跨域请求
CORS(app)

# 雪花算法生成id:能够确保id的唯一性
from snowflake.id_worker import IdWorker
app.id_worker = IdWorker(datacenter_id=Config.DATACENTER_ID,
                         worker_id=Config.WORKER_ID,
                         sequence=Config.SEQUENCE,)



from toutiao.apps.home import home_blueprint
from toutiao.apps.user import user_blueprint
# 注册home的蓝图
app.register_blueprint(home_blueprint)
# 注册user的蓝图
app.register_blueprint(user_blueprint)


from flask import request,g
from auth.auth_jwt import verify_token


@app.before_request
def before_request():
    """
    钩子函数:每次请求前判断请求头中的数据
    :return:
    """
    # 初始化变量
    g.user_id = None
    g.is_refresh_token = None

    authorization = request.headers.get("Authorization")
    # 如果请求头中有信息,并且数据接口是以Bearer为前缀,
    if authorization and authorization.startswith("Bearer "):
        # 获取Bearer后面的token数据
        token = authorization[7:]
        payload = verify_token(token)
        if payload:
            # 普通token
            g.user_id = payload.get("user_id")
            # refresh_token
            g.is_refresh_token = payload.get("refresh")

